const handlerGE = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
let isMove = false; // 记录当前是有实体在移动
handlerGE.setInputAction(event => {
  // 如果已经在移动状态就停止
  if (isMove) return;
  // 如果选中的不是实体就停止
  const entity = viewer.scene.drillPick(event.position, 1)[0];
  if (!entity) return;
  // 进入移动状态
  isMove = true;
  let diff = []; // 记录鼠标和各点的位置差异
  let type = null; // 记录选中的实体类型
  let positions = null; // 记录选中的实体位置
  let newPosition = null; // 记录选中的实体随鼠标变化后的位置
  const position = changeToThree(event.position); // 记录鼠标的位置
  if (entity.id.polygon) {
    if (!entity.id.polygon.hierarchy?._value) return;
    type = "polygon";
    positions = entity.id.polygon.hierarchy._value.positions;
  } else if (entity.id.polyline) {
    if (!entity.id.polyline.positions?._value) return;
    type = "polyline";
    positions = entity.id.polyline.positions._value;
  };
  // 记录鼠标和各点的位置差异
  positions.forEach(item => {
    diff.push({
      x: item.x - position.x,
      y: item.y - position.y,
      z: item.z - position.z,
    });
  });

  handlerGE.setInputAction(event => {
    const movePosition = changeToThree(event.endPosition);
    // 通过鼠标和各点的位置差异与鼠标位置计算实体新位置
    newPosition = diff.map(item => ({
      x: item.x + movePosition.x,
      y: item.y + movePosition.y,
      z: item.z + movePosition.z,
    }));
    // 根据实体类型创建新的实体
    if (type === "polygon") {
      entity.id.polygon.hierarchy = new Cesium.CallbackProperty(function() {
        return new Cesium.PolygonHierarchy(newPosition);
      }, false);
      entity.id.polyline.positions = new Cesium.CallbackProperty(function() {
        return newPosition.concat([newPosition[0]]);
      }, false);
    } else if (type === "polyline") {
      entity.id.polyline.positions = new Cesium.CallbackProperty(function() {
        return newPosition;
      }, false);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  handlerGE.setInputAction(() => {
    if (type === "polygon") {
      entity.id.polygon.hierarchy = newPosition;
      entity.id.polyline.positions = newPosition.concat([newPosition[0]]);
    } else if (type === "polyline") {
      entity.id.polyline.positions = newPosition;
    };
    // 初始化
    diff = [];
    type = null;
    positions = null;
    isMove = false;
    newPosition = null;
    handlerGE.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handlerGE.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);





viewer.selectedEntityChanged.addEventListener(entity => {
//   console.log(entity);
});
